<?php

namespace common\models;

use app\models\AdminLog;
use backend\behaviors\PositionBehavior;
use common\utils\XCache;
use phpDocumentor\Reflection\Types\This;
use Yii;

/**
 * This is the model class for table "catalog".
 *
 * @property string $id
 * @property string $name
 * @property string $us_name
 * @property string $alias
 * @property string $sort
 * @property string $parent_id
 * @property string $type
 * @property string $intro
 * @property string $link
 * @property string $created_at
 * @property string $created_by
 * @property string $updated_at
 * @property string $updated_by
 * @property string $view_list
 * @property string $view_show
 * @property string $view_item
 * @property string $frontend_nav
 * @property string $backend_nav
 * @property int $page_size
 *
 * @property Catalog $parent
 */
class Catalog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'catalog';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'alias'], 'required'],
            [['alias'], 'unique'],
            [['sort', 'parent_id', 'created_at', 'created_by', 'updated_at', 'updated_by', 'frontend_nav', 'backend_nav', 'page_size'], 'integer'],
            ['sort', 'default', 'value' => 1],
            ['parent_id', 'default', 'value' => 0],
            [['type'], 'in', 'range' => [1, 2, 3]],
            [['name', 'us_name','alias', 'view_list', 'view_show', 'view_item'], 'string', 'max' => 64],
            [['intro'], 'string', 'max' => 1000],
            [['link'], 'string', 'max' => 255],
            [['link'], 'url', 'defaultScheme' => 'http'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'us_name' => '英文名',
            'alias' => '别名',
            'sort' => '排序',
            'parent_id' => '父类id',
            'type' => '显示类型：1目录，2图文，3外链',
            'link' => '外链',
            'intro' => '摘要',
            'created_at' => '创建时间',
            'created_by' => '添加人',
            'updated_at' => '更新时间',
            'updated_by' => '更新人',
            'view_list' => '目录视图',
            'view_show' => '内容视图',
            'view_item' => '目录列表块',
            'frontend_nav' => '前台主导航',
            'backend_nav' => '后台控制面板',
            'page_size' => '分页大小',
        ];
    }

    public function attributeHints()
    {
        return ['frontend_nav' => '上级分类勾选才有效', 'page_size' => '展现方式为目录时才有效，不设置为20'];
    }

    public function behaviors()
    {
        return [
            'positionBehavior' => [
                'class' => PositionBehavior::className(),
                'positionAttribute' => 'sort',
                'groupAttributes' => ['parent_id'],
            ],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(Catalog::className(), ['id' => 'parent_id']);
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = $this->updated_at = time();
            $this->created_by = $this->updated_by = Yii::$app->user->id;
        } else {
            $this->updated_at = time();
            $this->updated_by = Yii::$app->user->id;
        }
        $this->sort < 1 && $this->sort = 1;
        $this->page_size < 0 && $this->page_size = 0;
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            AdminLog::log("新添栏目：" . $this->name, "create");
        } else {
            AdminLog::log("更新栏目：旧：" . $changedAttributes['name'] . "；新：" . $this->name);
        }
        XCache::catalogNavDelete();
        XCache::catalogDelete($this->alias);
        XCache::catalogDeleteById($this->id);
    }

    public function afterDelete()
    {
        parent::afterDelete();
        //删除子栏目
        $childes = $this->getChildIdes($this->id);
        if ($childes) {
            $this->deleteAll("id in(:ids)", [':ids' => $childes]);
        }
        //删除对应的meta
        Meta::del($this->tableName(), $this->id);
        //删除对应的素材关联
        ArticleTo::del($this->tableName(), $this->id);

        AdminLog::log("删除栏目：" . $this->name, "delete");

        XCache::catalogNavDelete();
        XCache::catalogDelete($this->alias);
        XCache::catalogDeleteById($this->id);
    }

    /**
     * @param $val int
     * @return mixed
     */
    public static function getType($val)
    {
        $types = ['目录', '图文', '外链'];
        return $types[$val - 1];
    }

    public static function typeList()
    {
        return ['1' => '目录', '2' => '图文', '3' => '外链'];
    }

    private $catalogTreeList = [];

    /**
     * 递归“---- ”树形栏目
     * @param array $catalogList
     * @param int $parentId
     */
    private function tree($catalogList, $parentId)
    {
        foreach ((array)$catalogList as $catalog) {
            if ($catalog['parent_id'] == $parentId) {
                $this->repeat = '';
                $this->getRepeat($catalogList, $catalog['parent_id']);
                $this->catalogTreeList = $this->catalogTreeList + [$catalog['id'] => $this->repeat . $catalog['name']];
                $this->tree($catalogList, $catalog['id']);
            }
        }
    }

    public function getList($condition = '', $params = [], $orderBy = [])
    {
        return $this->find()->where($condition, $params)->orderBy($orderBy)->all();
    }

    /**
     * 获取“---- ”树形栏目
     * @param int $parentId
     * @param string $condition
     * @param array $params
     * @return array
     */
    public function getTrees($parentId = 0, $condition = '', $params = [])
    {
        $this->tree($this->getList($condition, $params), $parentId);
        return $this->catalogTreeList;
    }

    private $repeat;

    /**
     * 反向设置repeat
     * @param array $catalogList
     * @param int $parentId 父类id
     * @return string
     */
    private function getRepeat($catalogList, $parentId)
    {
        if ($parentId === 0) {
            return '';
        }
        foreach ((array)$catalogList as $catalog) {
            if ($catalog['id'] == $parentId) {
                $this->repeat .= '---- ';
                if ($catalog['parent_id'] === 0) {
                    break;
                } else {
                    $this->getRepeat($catalogList, $catalog['parent_id']);
                }
            }
        }
    }

    private $childIdes = [];

    public function getChildId($catalogList, $parentId = 0)
    {
        foreach ((array)$catalogList as $catalog) {
            if ($catalog['parent_id'] == $parentId) {
                //$this->childIdes = $this->childIdes + $catalog['id'];
                array_push($this->childIdes, $catalog['id']);
                $this->getChildId($catalogList, $catalog['id']);
            }
        }
    }

    public function getChildIdes($parentId = 0, $condition = '', $params = [])
    {
        $this->getChildId($this->getList($condition, $params), $parentId);
        if ($this->childIdes) {
            return implode(',', $this->childIdes);
        } else {
            return null;
        }
    }

    /***
     * @param int $depth 深度，目前只支持1和2，默认为1
     * @return array 前台主导航
     */
    public static function getNavItems($depth = 1,$alias='')
    {
        /*if ($depth == 1) {
            return Catalog::find()->select('alias,name')->where("parent_id=0 and frontend_nav=1")->orderBy("sort ASC, id ASC")->asArray()->all();
        } elseif ($depth == 2) {
            $list = [];
            $data = Catalog::find()->select('id,parent_id,alias,name')->where('frontend_nav=1')->orderBy("sort ASC, id ASC")->asArray()->all();
            $n = 0;
            foreach ((array)$data as $item) {
                if ($item['parent_id'] === '0') {
                    $list[$n] = ['alias' => $item['alias'], 'name' => $item['name']];
                    foreach ((array)$data as $value) {
                        if ($item['id'] == $value['parent_id']) {
                            $list[$n]['childItems'][] = ['alias' => $value['alias'], 'name' => $value['name']];
                        }
                    }
                    $n++;
                }
            }
            return $list;
        }
        return [];*/
        if($depth==3&&$alias){
            return XCache::catalogAliasNav($alias);
        }else {
            return XCache::catalogNav($depth);
        }
    }

    /**
     * 返回一级父类
     * @param $id
     * @return static Catalog
     */
    public static function getFirstParent($id)
    {
        if (!$id)
            return [];
        $model = static::findOne($id);
        if ($model->parent_id) {
            return static::getFirstParent($model->parent_id);
        }
        return $model;
    }
}
